// pages/chatroom/chatroom.js
const formTime = require('../../utils/formTime.js')
const db = wx.cloud.database()
const _ = db.command
Page({

  /**
   * 页面的初始数据
   */
  data: {
    id:'',
    InputBottom: 0,
    openid:'',
    targetid:'',
    userinfo:{},
    avatarUrl:'',
    messageData:[],
    newMessage:'',
    lastId:'',
    input_bottom:0,
    bookname:'',
    bookprice:'',
    publishinfo:{}
  },

  // onSubscribe: function(){
  //   wx.requestSubscribeMessage({
  //     // tmplIds: ['t2r26N3WvkUIKJ3eMI1cpgoYlvvR3K6qpiHjpQmvQI4'],
  //     tmplIds: ['t2r26N3WvkUIKJ3eMI1cps-1oYn1-Sh5Y0Be89rOftM'],

  //     success(res){
  //       console.log('授权成功',res)
  //     },
  //     fail(res){
  //       console.log('授权失败',res)
  //     }
  //   })
  // },

    //跳转详情
  detail(e) {
      let that = this;
      wx.navigateTo({
            url: '/pages/detail/detail?scene=' + e.currentTarget.dataset.id,
      })
  },

  focus:function(e){
    this.setData({
      input_bottom:270
    })
  },
  no_focus:function(e){
    this.setData({
      input_bottom:2
    })
  },

  InputFocus(e) {
    this.setData({
      InputBottom: e.detail.height
    })
  },
  InputBlur(e) {
    this.setData({
      InputBottom: 0
    })
  },

  content(e){
    this.setData({
      newMessage:e.detail.value
    })
  },
  send(){
    let that = this
    if(that.data.newMessage === ''){
      wx.showToast({
        title: '请输入内容',
        icon: 'error',
        mask: true,
      })
      }else{
        // that.data.messageData.push({
        //   text:that.data.newMessage,
        //   time:'刚刚',
        //   openid:that.data.openid,
        //   type:'文字'
        // })
        db.collection('message').doc(that.data.id).update({
          data:{
            // done:false,
            content:_.push({
              openid:that.data.openid,
              time:formTime.formTime(new Date()),
              text:that.data.newMessage,
              type:'文字'
            }),
            
          }
        })
        that.setData({
          newMessage:'',
          // messageData:that.data.messageData,
          // lastId:"msg-" + that.data.messageData.length-1
        })
        var flag = false
        db.collection('subscribe').get().then(res=>{
          for(let item of res.data){
            if(item.targetid === that.data.targetid){
              flag = true;
              break;
            }
          }
        })
        setTimeout(function(){
          if(flag === false){
            db.collection('subscribe').add({
              data:{
                targetid:that.data.targetid,
                time:formTime.formTime(new Date())
              }
            })
          }
        },10000 ); 
        // this.onSubscribe()
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(e) {
    let that = this
    wx.getStorage({
      key:'userinfo',
      success(res){
        console.log('userinfo',res);
        that.setData({
          userinfo: res.data,
          avatarUrl:res.data.avatarUrl,
          id:e._id
        })
      },
      fail(res){
        console.log('failuserinfo',res);
      }
    })
    wx.getStorage({
      key:'openid',
      success(res){
        //console.log('成功获取缓存中的openid',res)
        that.setData({
          openid:res.data
        })
      }
    })
    this.getContent(e._id);
  },

  getContent(e){
    let that = this;
            db.collection('message').doc(e).get({
                  success: function(res) {
                    console.log('获取消息成功：',res)
                  //  arr = res.result.data
                  //   for(let item of arr){
                  //     if(item._openid !== that.data.openid){ //判断当前openid是否是自己的，若不是则与userid进行交换
                  //       let tmp = item.targetid
                  //       item.targetId = item._openid
                  //       item._openid = tmp
                  //     }
                  //   }
                  if(res.data._openid !== that.data.openid){
                    that.setData({
                      targetid:res.data._openid
                    })
                  }else{
                    that.setData({
                      targetid:res.data.targetid
                    })
                  }
                  if('publishinfo' in res.data){
                    that.setData({
                      messageData : res.data.content,
                      publishinfo: res.data.publishinfo[res.data.publishinfo.length-1]
                    })
                  }else{
                    that.setData({
                      messageData : res.data.content,
                      bookname:res.data.bookname,
                      bookprice:res.data.bookprice
                    })
                  }
                        setTimeout(function () {
                          that.setData({
                            lastId:"msg-" + (res.data.content.length-1)
                          })
                        }, 100)
                        // console.log('lastId：',"msg-" + (res.data.content.length-1))
                  }
            })

  },

  submit:function(e){
    console.log("发送的信息：",e);
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    let that = this
    const watcher = db.collection('message').doc(that.data.id).watch({
      onChange: function(snapshot){
        console.log('snapshot',snapshot);
        that.setData({
          messageData:snapshot.docs[0].content,
          lastId:"msg-" + (snapshot.docs[0].content.length-1)
        })
      },
      onError: function(err) {
        console.error('the watch closed because of error', err)
      }
    })
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})